﻿using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;

// Copy http://www.blueedge.nl/weblog/post/WCF-ExceptionHandling-in-Silverlight.aspx

namespace MailRuWrapper.Server.Silverlight
{
    /// <summary>
    /// See http://msdn.microsoft.com/en-us/library/dd470096(VS.96).aspx
    /// </summary>
    internal class WcfSilverlightFaultBehavior : IDispatchMessageInspector
    {
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault) return;
            var _property = new HttpResponseMessageProperty {StatusCode = System.Net.HttpStatusCode.OK};

            // Here the response code is changed to 200.

            reply.Properties[HttpResponseMessageProperty.Name] = _property;
        }

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            // Do nothing to the incoming message.
            return null;
        }
    }

    /// <summary>
    /// Позволяет корректно передавать стандартные Fault исключения в Silverlight 
    /// Требует аттрибуты [FaultContract(typeof(...MyCustomException...))] в контракте сервиса
    /// и DataContract, DataMember для MyCustomException
    /// </summary>
    public sealed class WcfSilverlightFaultBehaviorAttribute : WcfBehaviorAttributeBase
    {
        public WcfSilverlightFaultBehaviorAttribute()
            : base(typeof(WcfSilverlightFaultBehavior))
        {
        }
    }
}


